use crate::models::Word;
use std::io::Result;

pub fn parse_csv(content: &str) -> Result<Vec<Word>> {
    let mut words = Vec::new();
    let mut reader = csv::ReaderBuilder::new()
        .has_headers(false)
        .flexible(true) // 允许可变列数
        .from_reader(content.as_bytes());

    for result in reader.records() {
        let record = result.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        if !record.is_empty() {
            // 确保至少有2个字段，处理可能的空行或不完整行
            if record.len() >= 2 {
                words.push(Word {
                    word: record[0].trim().to_string(), // 去除首尾空白
                    meaning: record[1].trim().to_string(), // 去除首尾空白
                });
            } else if record.len() == 1 {
                // 如果只有一列，跳过或记录警告
                eprintln!("警告: CSV行格式不完整 - {:?}", record);
            }
        }
    }

    Ok(words)
}

pub fn parse_txt(content: &str) -> Result<Vec<Word>> {
    let mut words = Vec::new();
    
    for line in content.lines() {
        let line = line.trim();
        
        // 跳过空行和注释行（以#开头的行）
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        // 匹配格式：word [meaning1;meaning2;meaning3]
        if let Some(start) = line.find('[') {
            if let Some(end) = line.find(']') {
                let word = line[..start].trim().to_string();
                let meanings: Vec<&str> = line[start + 1..end].split(';').collect();
                let meaning = meanings.iter().map(|s| s.trim()).collect::<Vec<_>>().join("; ");

                words.push(Word { word, meaning });
            }
        } else {
            // 如果不匹配特殊格式，则按空格分割处理
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 2 {
                let word = parts[0].to_string();
                let meaning = parts[1..].join(" ");

                words.push(Word { word, meaning });
            }
        }
    }

    Ok(words)
}